﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebTraderLiteCL;

namespace WebTraderLite.Pages
{
    public partial class StockGraph : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnGraph_Click(object sender, EventArgs e)
        {
            
            Stock stk = new Stock(tbStock.Text);

            if (stk.CompanyName.Equals("NULL"))
            {
                //Unknown symbol
                Label lbl = new Label();
                lbl.Text = "Stock sybmol " + stk.Symbol + " not found";
                lbl.Font.Bold = true;
                lbl.ForeColor = System.Drawing.Color.Red;
                phFailSearch.Controls.Add(lbl);

            }
            else
            {
                stockDataQuery qry = new stockDataQuery();
                DateTime fromDate = DateTime.Parse(tbBeginDate.Text.Trim());
                DateTime toDate   = DateTime.Parse(tbEndDate.Text.Trim());

                List<HistoricalStockData> history = qry.getHistoricalData(tbStock.Text, fromDate, toDate);

                foreach(HistoricalStockData elem in history)                
                {
                    stockChart.Series["seriesPriceHistory"].Points.AddXY(elem.Date, elem.Close);
                    stockChart.Series["seriesVolHistory"].Points.AddXY(elem.Date, elem.Volume);
                }

                double maxClose = history.Max(t => t.Close);
                double minClose = history.Min(t => t.Close);

                //Set the axis titles
                stockChart.Titles.Add(stk.CompanyName + " history from " + fromDate.ToShortDateString() + " to " + toDate.ToShortDateString());
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisX.Title = "Date";
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisY.Title = "Closing Price ($)";

                stockChart.ChartAreas["chartAreaVolume"].AxisX.Title = "Date";
                stockChart.ChartAreas["chartAreaVolume"].AxisY.Title = "Volume";                

                //Set the max and min of the Y-axis
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisY.Maximum = maxClose;
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisY.Minimum = minClose;
            }
        }
    }
}